<template>
  <div class="settle-wrapper">
    <div class="settle-content">
      <Breadcrumb class="breadcrumb" :crumbs="crumbs"></Breadcrumb>
      <div class="title">投资机构认证：</div>

      <div class="settle-select">
        <div class="select-industry">
          <div class="industry-title">投资行业(多选)：</div>
          <div class="industry-option">
            <div
              class="option-div"
              :class="{ 'option-active': limitSwith }"
              @click="onIndustry({ id: -1 }, 'limit')"
            >
              不限
            </div>
            <div
              v-for="(item, index) in industry"
              :key="index"
              class="option-div"
              :class="{
                'option-active': industryArr.indexOf(item.dictValue) != -1,
              }"
              @click="onIndustry(item, 'indus')"
            >
              {{ item.dictLabel }}
            </div>
          </div>
        </div>
        <div class="select-industry">
          <div class="industry-title">投资方式：</div>
          <div class="industry-option">
            <div
              class="option-div"
              :class="{ 'option-active': limitSwith2 }"
              @click="onIndustry({ id: -1 }, 'limit2')"
            >
              不限
            </div>
            <div
              v-for="(item, index) in mode"
              :key="index"
              class="option-div"
              :class="{
                'option-active': modeArr.indexOf(item.dictValue) != -1,
              }"
              @click="onIndustry(item, 'mode')"
            >
              {{ item.dictLabel }}
            </div>
          </div>
        </div>
      </div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        class="demo-ruleForm"
        label-position="left"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="机构联系人姓名：" prop="contactsPerson">
              <el-input
                v-model.trim="ruleForm.contactsPerson"
                placeholder="请输入机构联系人姓名"
                maxlength="10"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="联系方式：" prop="contactsPhone">
              <el-input
                v-model.trim="ruleForm.contactsPhone"
                placeholder="请输入联系方式"
                maxlength="13"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="企业授权证明：" prop="authorizationFile">
          <addImgUpload @changeImgUp="changeImgUpProve" @deleteImgUp="deleteImgUpProve"></addImgUpload>
        </el-form-item>
        <el-row>
          <el-col :span="10">
            <el-form-item label="授权人姓名：" prop="authorizer">
              <el-input
                v-model.trim="ruleForm.authorizer"
                placeholder="请输入授权人姓名"
                maxlength="10"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="授权人身份证号：" label-width="135px" prop="authorizerIdNo">
              <el-input
                v-model.trim="ruleForm.authorizerIdNo"
                placeholder="请输入授权人身份证号"
                maxlength="18"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <el-form-item label="企业营业执照：" prop="manageLicense">
            <addImgUpload @changeImgUp="changeImgUpLicense" @deleteImgUp="deleteImgUpLicense"></addImgUpload>
          </el-form-item>
        </div>

        <el-form-item label="投资规模：" prop="investmentScale">
          <el-input
          @input="changeInvestmentScale"
            :value="ruleForm.investmentScale"
            placeholder="请输入投资规模"
            style="width: 300px"
            type="number"
          >
            <div slot="append">万元</div>
          </el-input>
        </el-form-item>
        <el-form-item label="投资机构介绍:" prop="introduction">
          <el-input
            type="textarea"
            v-model.trim="ruleForm.introduction"
            resize="none"
            maxlength="5000"
            :rows="4"
            class="reason-input"
            placeholder="请输入介绍，不超过5000个字符..."
            style="width: 500px"
            :show-word-limit="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="投资案例：" prop="investmentCase">
          <addUpload @changeUp="changeUp"></addUpload>
        </el-form-item>

        <el-form-item label="" prop="readAgree">
          <el-checkbox v-model.trim="ruleForm.readAgree"
            >阅读并同意《投资机构入驻协议》</el-checkbox
          >
        </el-form-item>

        <div>
          <el-form-item>
            <Buttons :buttons="buttons" @goBack="goBack" @apply="submitForm('ruleForm')" class="btns"></Buttons>
            <!-- <el-button type="primary" @click="goBack()" class="cancelBtn"
              >返回</el-button
            >
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
              class="cancelBtn apply-btn"
              :loading="isLoading"
              >{{isLoading ? '提交中...' : '提交'}}</el-button
            > -->
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import Breadcrumb from "@/components/breadcrumb";
import addImgUpload from "./components/financiaImgUpload";
import addUpload from "@/components/financiaUpload";
import {checkLogin,relogin} from '@/utils/util.js'
import { getCompanyInvestmentAdd } from '@/common/api/finance'
export default {
  components: {
    Breadcrumb,
    addImgUpload,
    addUpload,
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      var Regx =
        /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,1,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/; //手机号正则
      if (value === "") {
        callback(new Error("请输入联系电话"));
      } else if (!Regx.test(value)) {
        callback(new Error("联系电话格式不正确!"));
      } else {
        callback();
      }
    };

    var birthDay = (rule, value, callback) => {
      var bir =
        /^[1-9]\d{5}(|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; //身份证日期正则
      var pattern =
        /^((19[2-9]\d{1})|(20((0[0-9])|(1[0-8]))))\-((0?[1-9])|(1[0-2]))\-((0?[1-9])|([1-2][0-9])|30|31)$/; // 验证出生年月
      var birthday = `${value.substr(6, 4)}-${value.substr(
        10,
        2
      )}-${value.substr(12, 2)}`;
      console.log(pattern.test(birthday));
      console.log(birthday);
      if (value === "") {
        callback(new Error("请输入身份证号"));
      } else if (!bir.test(value)) {
        console.log(value);
        callback(new Error("身份证号不正确!"));
      } else if (!pattern.test(birthday)) {
        console.log(value);
        callback(new Error("出生年月不正确!"));
      } else {
        callback();
      }
    };

    return {
      buttons:[
        {text:"取消",type:"normal",size:"l",method:"goBack"},
        {text:"提交",type:"success",size:"l",method:"apply"},
      ],
      isLoading: false,
      crumbs: [
        {
          label: "金融服务",
          value: "finance",
        },
        {
          label: "投资机构入驻",
          value: "financeSettle",
          choose: true,
        },
      ],
      industry: [],
      industryArr: [],
      limitSwith: true,
      limitSwith2: true,
      mode: [],
      modeArr: [],
      ruleForm: {
        contactsPerson: "",
        contactsPhone: "",
        authorizer: "",
        introduction: "",
        authorizationFile: "",
        authorizerIdNo: "",
        manageLicense: "",
        investmentScale: "",
        investmentCase: "",
        readAgree: "",
      },
      rules: {
        contactsPerson: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入机构联系人姓名"));
              } else if (!/^[\u4E00-\u9FA5]+$/.test(value)) {
                callback(new Error("请输入汉字"));
              } else {
                callback();
              }
            },
          },
        ],
        contactsPhone: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入联系方式"));
              } else if (!/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/.test(value)) {
                callback(new Error("请输入正确的联系方式"));
              } else {
                callback();
              }
            },
          },
        ],
        introduction: [
          { required: true, message: "请填写投资机构介绍", trigger: "blur" },
        ],
        authorizer: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入授权人姓名"));
              } else if (!/^[\u4E00-\u9FA5]+$/.test(value)) {
                callback(new Error("请输入汉字"));
              } else {
                callback();
              }
            },
          },
        ],
        authorizerIdNo: [
          // { required: true, message: "请输入授权人身份证号", trigger: "blur" },
          { required: true, validator: birthDay, trigger: "blur" },
        ],
        authorizationFile: [
          { required: true, message: "请上传企业授权证明", trigger: "change" },
        ],
        manageLicense: [
          { required: true, message: "请上传企业营业执照", trigger: "change" },
        ],
        investmentScale: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              console.log(value);
              if (value === "") {
                callback(new Error("请填写投资规模"));
              } else if (!/^\d+$|^\d+[.]?\d+$/.test(value)) {
                callback(new Error("请输入数字"));
              } else {
                callback();
              }
            },
          },
        ],
        readAgree: [
          { required: true, trigger: "change",             
            validator: (rule, value, callback) => {
              if (value) {
                callback();
              } else {
                callback(new Error("请勾选协议"));
              }
            }, 
          },
        ],
      },
    };
  },
  methods: {
    // 删除企业授权证明
    deleteImgUpProve(){
      this.ruleForm.authorizationFile = ""
    },
    // 删除企业营业执照
    deleteImgUpLicense(){
      this.ruleForm.manageLicense = ""
    },
    // 对投资规模内容做出限制
    changeInvestmentScale(e){
      if(e.length <= 21){
        if(e.indexOf(".") != -1){
          if((e.indexOf(".")+3) <= e.length){
            e = e.slice(0,e.indexOf(".")+3)
            this.ruleForm.investmentScale = e
          }
          this.ruleForm.investmentScale = e
        }
        if(e.length <= 18){
          this.ruleForm.investmentScale = e
        }
      }
    },
    /**
     * 上传文件触发
     * @param obj 上传文件数据
     * @return {void}
     */
    changeUp(obj) {
      let arr = [];
      // for (let i in obj) {
      //   arr.push(obj[i].batchId);
      // }
      this.ruleForm.investmentCase = obj[0].batchId;
      this.$refs["ruleForm"].validateField("investmentCase");
    },
    /**
     * 上传企业授权触发
     * @param obj 上传文件数据
     * @return {void}
     */
    changeImgUpProve(obj) {
      let arr = [];
      // for (let i in obj) {
      //   arr.push(obj[i].batchId);
      // }
      this.ruleForm.authorizationFile = obj[0].batchId;
      this.$refs["ruleForm"].validateField("authorizationFile");
    },
    /**
     * 上传企业营业执照触发
     * @param obj 上传文件数据
     * @return {void}
     */
    changeImgUpLicense(obj) {
      let arr = [];
      // for (let i in obj) {
      //   arr.push(obj[i].batchId);
      // }
      this.ruleForm.manageLicense = obj[0].batchId;
      this.$refs["ruleForm"].validateField("manageLicense");
    },
    /**
     * 立即申请触发
     * @param formName 表单
     * @return {void}
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.investmentRealms = this.industryArr.length
            ? this.industryArr.join(",")
            : "-1";
          this.ruleForm.financingTypes = this.modeArr.length
            ? this.modeArr.join(",")
            : "-1";
          console.log(11111, this.ruleForm);
          this.subForm();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /**
     * 提交请求接口
     * @param {void}
     * @return {void}
     */
    async subForm() {
      this.isLoading = true
      let { code, msg } = await getCompanyInvestmentAdd(this.ruleForm)
       if (code != '200') return this.$message.warning(msg)
      this.$alert(`<div class="alert_msg"><img src="${require('@/assets/image/finance/success.png')}"><p class="title">投资入驻资料提交成功！</p><p class="text">请您耐心等待审核结果，审核结果将以短信的方式发送至您的手机。</p></div>`, "", {dangerouslyUseHTMLString: true, showConfirmButton: false, beforeClose: (action, instance, done) => {
        this.$router.push({ path: "finance" });
        done()
      }})
      this.isLoading = false
    },
    // 返回
    goBack: function () {
      this.$router.back();
    },
    /**
     * 多选触发
     * @param obj 数据值
     * @param type 区别类型
     * @return {void}
     */
    onIndustry(obj, type) {
      if (type == "indus") {
        if (this.industryArr.indexOf(obj.dictValue) !== -1) {
          this.industryArr.splice(this.industryArr.indexOf(obj.dictValue), 1); //取消
        } else {
          this.industryArr.push(obj.dictValue); //选中添加到数组里
        }
        this.limitSwith = false;
      } else if (type == "limit") {
        this.limitSwith = true;
        this.industryArr = [];
      } else if (type == "limit2") {
        this.limitSwith2 = true;
        this.modeArr = [];
      } else {
        if (this.modeArr.indexOf(obj.dictValue) !== -1) {
          this.modeArr.splice(this.modeArr.indexOf(obj.dictValue), 1); //取消
        } else {
          this.modeArr.push(obj.dictValue); //选中添加到数组里
        }
        this.limitSwith2 = false;
      }
    },
    // 获取字典表
    async getIndustryTypeList() {
      let api = `company_industry,finance_financing_type`;
      // 调用公共方法中的查询字典表
      this.getDictList(this, api).then((res) => {
        this.mode = res.data.finance_financing_type;
        this.industry = res.data.company_industry;
      })
    },
  },
  mounted() {
    if(checkLogin(this)){
      this.getIndustryTypeList();
    } else {
      // console.log('123')
      relogin(this);
    }
  },
};
</script>
<style lang="scss" scoped>
.settle-content {
  width: 1200px;
  margin: 0 auto;
  text-align: left;
}
.breadcrumb {
  width: 1200px;
  margin: 20px 0;
}
.title {
  font-size: 24px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 15px;
}
.settle-select {
  width: 100%;
  border: 1px solid#eeeeee;
  margin-bottom: 40px;
}
.settle-select .select-industry {
  width: 100%;
  display: flex;
  border-bottom: 1px solid #eeeeee;
}
.settle-select .select-industry:last-child {
  border: none;
}
.settle-select .select-industry .industry-title {
  padding: 16px 0;
  width: 168px;
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  background: #eeeeee;
  display: flex;
  display: -webkit-flex;
  align-items: center;
  justify-content: center;
}
.settle-select .select-industry .industry-option {
  color: #666666;
  font-size: 14px;
  display: flex;
  display: -webkit-flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 0 20px;
  width: calc(100% - 170px);
}
.settle-select .select-industry .industry-option .option-div {
  margin-right: 15px;
  padding: 5px 8px;
  cursor: pointer;
  margin: 5px;
}
.settle-select .select-industry .industry-option .option-active {
  background: #d00000;
  color: #fff;
  border-radius: 4px;
}

.cancelBtn {
  border: 1px solid #eeeeee;
  display: inline-block;
  font-size: 14px;
  background: #ffff;
  color: #415465;
  padding: 13px 35px;
  text-align: center;
  border-radius: 5px;
  margin-right: 10px;
}

.cancelBtn:hover {
  cursor: pointer;
  box-shadow: 0px 0px 5px #eeeeee;
}

.apply-btn {
  border: 1px solid #0053bc;
  background: #0053bc;
  color: #fff;
}

.apply-btn:hover {
  cursor: pointer;
  box-shadow: 0px 0px 5px #0053bc;
}
.btns{
  justify-content: left !important;
}
</style>
